package com.way.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.way.dto.ConsumptionMessageDto;
import com.way.dto.WeiXinMessageDto;
import com.way.enums.LangEnum;
import com.way.enums.MiniProgramStateEnum;
import com.way.service.IWeiXinMessageService;
import com.way.util.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WeiXinMessageService implements IWeiXinMessageService {

    @Value("${weiXin.message_url}")
    private String messageUrl;

    @Value("${weiXin.access_token_url}")
    private String accessTokenUrl;

    @Value("${weiXin.grant_type}")
    private String grantType;

    @Value("${weiXin.appId}")
    private String appId;

    @Value("${weiXin.secret}")
    private String secret;

    @Value("${weiXin.template_id}")
    private String templateId;

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Override
    public String getAccessToken() {
        String url = String.format(accessTokenUrl, grantType, appId, secret);
        String response = restTemplateUtil.sendGet(url);
        JSONObject object = JSON.parseObject(response);
        return object.get("access_token").toString();
    }

    @Override
    public String sendWeiXinMessage() {
        String accessToken = getAccessToken();
        String url = String.format(messageUrl, accessToken);

        ConsumptionMessageDto detail = new ConsumptionMessageDto();
        detail.setName1(setValue("米奇"));
        detail.setAmount2(setValue("1000.00"));
        detail.setAmount3(setValue("998.00"));
        detail.setTime4(setValue("2020-07-20"));

        WeiXinMessageDto dto = new WeiXinMessageDto();
        dto.setTouser("oeKmX5ImCoZF8RwuO7d_M6g-2-Ns");
        dto.setTemplate_id(templateId);
        dto.setMiniprogram_state(MiniProgramStateEnum.TRIAL.value);
        dto.setLang(LangEnum.ZH_CN.value);
        dto.setData(detail);

        return restTemplateUtil.sendPost(url, JSON.toJSONString(dto));
    }

    private JSONObject setValue(Object value) {
        JSONObject json = new JSONObject();
        json.put("value",value);
        return json;
    }
}
